package com.example.yskjproject.view.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.yskjproject.R;
import com.example.yskjproject.content.EventContent;
import com.example.yskjproject.event.EventMessage;
import com.example.yskjproject.http.APIService;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.LoginModel;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.model.WxLoginModel;
import com.example.yskjproject.model.WxScanCodeModel;
import com.example.yskjproject.utils.CashUtil;
import com.example.yskjproject.utils.EventBusUtil;
import com.example.yskjproject.utils.Log;
import com.example.yskjproject.utils.SpCashUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.qcloud.tuicore.util.ToastUtil;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 登录显示的dialog
 */
public class LoginDialogHelper extends Dialog {


    private AppCompatImageView imageView;
    private AppCompatEditText editPhone, edCode;
    private AppCompatCheckBox checkBox;

    private AppCompatTextView codeNumber;

    private Gson gson = new Gson();

    private LoginWxDialogHelper loginWxDialogHelper;

    private long currentTimeMillis;//获取图片的时间

    private CountDownTimer countDownTimer;

    private Context context;


    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 0://完成
                    removeMessages(1);
                    loginWxDialogHelper = new LoginWxDialogHelper(getContext());
                    loginWxDialogHelper.show();
                    dismiss();
                    break;
                case 1://去查询
                    Map<String, String> jsonParams = new HashMap<>();
                    jsonParams.put("ticket", SpCashUtils.getInstance().getTicket());
                    jsonParams.put("device_token", SpCashUtils.getInstance().getDeviceToken());
                    String paramsDate = gson.toJson(jsonParams);
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
                    new Thread(()-> OkGo.<LzyResponse<WxLoginModel>>post(Urls.LOOP_WX_LOGIN).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<WxLoginModel>>() {
                        @SuppressLint("SimpleDateFormat")
                        @Override
                        public void onSuccess(Response<LzyResponse<WxLoginModel>> response) {
                            WxLoginModel wxLoginModel = response.body().data;
                            if (wxLoginModel != null) {
                                switch (wxLoginModel.getLogin_state()) {
                                    case 0://未扫码
                                        if(mHandler != null){
                                            mHandler.removeMessages(1);
                                            //间隔时间
                                            mHandler.sendEmptyMessageDelayed(1, 1000);
                                        }
                                        break;
                                    case 2://扫码成功 但没有绑定手机号
                                        if(mHandler != null){
                                            mHandler.sendEmptyMessage(0);
                                        }
                                        break;
                                    case 1://成功  直接登录
                                        if (wxLoginModel.getLogin_resp() != null) {
                                            SpCashUtils.getInstance().setToken(wxLoginModel.getLogin_resp().getAccess_token());
                                            SpCashUtils.getInstance().setTokenTime(wxLoginModel.getLogin_resp().getRefresh_after());
//                                            SpCashUtils.getInstance().setCurrentTokenTime(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance()));
                                            EventBusUtil.sendEvent(new EventMessage(EventContent.Login_Update));
                                            dismiss();
                                        }
                                        break;

                                }
                            }
                        }

                        @Override
                        public void onError(Response<LzyResponse<WxLoginModel>> response) {
                            super.onError(response);
                        }
                    })).start();
                    break;
                case 100:// 检测二维码是不是过期
                    if (CashUtil.getInstance().getTime() < (int) ((System.currentTimeMillis() - currentTimeMillis) / 1000)) {
                        getNetWxCode(imageView);
                    } else {
                        setWxCodeHandler();
                    }
                    break;

            }
        }
    };

    public LoginDialogHelper(@NonNull Context context) {
        super(context);
        setContentView(R.layout.login_dialog);
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        int layoutWidth;
        int layoutHeight;
        if (window != null) {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int screenWidth = displayMetrics.widthPixels;
            int screenHeight = displayMetrics.heightPixels;
            if (screenWidth > 3000) {
                layoutWidth = (int) (screenWidth * 0.5f);
                layoutHeight = (int) (screenHeight * 0.6f); // 保持原始宽高比
            } else {
                layoutWidth = (int) (screenWidth * 0.8f);
                layoutHeight = (int) (screenHeight * 0.3f);
            }
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.width = layoutWidth;
            layoutParams.height = layoutHeight;
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            window.setAttributes(layoutParams);
        }
        setCanceledOnTouchOutside(true);
        imageView = findViewById(R.id.img_code);
        getNetWxCode(imageView);
        editPhone = findViewById(R.id.ed_phone);
        edCode = findViewById(R.id.ed_code);
        checkBox = findViewById(R.id.login_checkbox);
        codeNumber = findViewById(R.id.phone_code_tv);

        //获取手机验证码
        codeNumber.setOnClickListener(code -> {
            if (TextUtils.isEmpty(editPhone.getText().toString().trim())) {
                ToastUtil.toastShortMessage("请输入手机号!");
                return;
            }
            if (editPhone.getText().toString().length() < 10) {
                ToastUtil.toastShortMessage("请输入正确的手机号!");
                return;
            }

            OkGo.<LzyResponse>get(Urls.YZM_CODE + "?mobile=" + editPhone.getText().toString().trim() + "&type=" + 1).execute(new JsonCallback<LzyResponse>() {
                @Override
                public void onSuccess(Response<LzyResponse> response) {
                    if (TextUtils.equals("ok", response.body().msg)) {
                        ToastUtil.toastShortMessage("获取手机验证码成功!");
                        countDownTimer = new CountDownTimer(60000, 1000) {
                            @SuppressLint("SetTextI18n")
                            public void onTick(long millisUntilFinished) {
                                codeNumber.setText(millisUntilFinished / 1000 + "s");
                            }

                            public void onFinish() {
                                codeNumber.setText("获取验证码");
                            }
                        }.start();

                    } else {
                        ToastUtil.toastShortMessage("获取手机验证码失败!");
                    }
                }

                @Override
                public void onError(Response<LzyResponse> response) {
                    super.onError(response);
                    ToastUtil.toastShortMessage(response.message());
                }
            });
        });

        findViewById(R.id.btn_login).setOnClickListener(login -> {
            if (TextUtils.isEmpty(editPhone.getText().toString().trim())) {
                ToastUtil.toastShortMessage("请输入手机号!");
                return;
            }

            if (TextUtils.isEmpty(edCode.getText().toString().trim())) {
                ToastUtil.toastShortMessage("请输入验证码!");
                return;
            }

            if (!checkBox.isChecked()) {
                ToastUtil.toastShortMessage("请勾选同意事项!");
                return;
            }
            Map<String, String> jsonParams = new HashMap<>();
            jsonParams.put("mobile", editPhone.getText().toString().trim());
            jsonParams.put("code", edCode.getText().toString().trim());
            jsonParams.put("ticket", "");
            jsonParams.put("device_token", SpCashUtils.getInstance().getDeviceToken());
            String paramsDate = gson.toJson(jsonParams);
            Log.e("参数：" + paramsDate);
            Log.e("url:" +  Urls.YZM_LOGIN);
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
            OkGo.<LzyResponse<LoginModel>>post(Urls.YZM_LOGIN).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<LoginModel>>() {
                @Override
                public void onSuccess(Response<LzyResponse<LoginModel>> response) {
                    LoginModel loginModel = response.body().data;
                    if (loginModel != null) {
                        SpCashUtils.getInstance().setToken(loginModel.getAccess_token());
//                        SpCashUtils.getInstance().setCurrentTokenTime(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance()));
                        SpCashUtils.getInstance().setTokenTime(loginModel.getRefresh_after());
                        EventBusUtil.sendEvent(new EventMessage(EventContent.Login_Update));
                        dismiss();
                    }else {
                        ToastUtil.toastShortMessage("登录数据返回为null");
                    }
                }

                @Override
                public void onError(Response<LzyResponse<LoginModel>> response) {
                    int code  = response.code();
                    super.onError(response);
                    ToastUtil.toastShortMessage(response.message() + ".");
                }
            });
        });


    }

    /**
     * 获取微信code 二维码
     */
    private void getNetWxCode(AppCompatImageView imageView) {
        Type type = new TypeToken<LzyResponse<WxScanCodeModel>>() {
        }.getType();
        APIService.<LzyResponse<WxScanCodeModel>>getData(type, Urls.WX_CODE).subscribeOn(Schedulers.io()).map(response -> response.data).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<WxScanCodeModel>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.e("onSubscribe ： " + d);
            }

            @Override
            public void onNext(WxScanCodeModel wxScanCodeModel) {
                if (TextUtils.isEmpty(wxScanCodeModel.getImg_url())) {
                    ToastUtil.toastShortMessage("二维码为空！");
                    return;
                }

                Glide.with(context).load(wxScanCodeModel.getImg_url())
                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(40)))//圆角半径
                        .into(imageView);

                SpCashUtils.getInstance().setTicket(wxScanCodeModel.getTicket());
                //有效时间
                CashUtil.getInstance().setTime(wxScanCodeModel.getExpire_seconds() - 50);
                //获取当前时间
                currentTimeMillis = System.currentTimeMillis(); // 获取当前时间的时间戳（毫秒）
                setHandler();
                setWxCodeHandler();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();            //请求失败
                Log.e("onError ： " + "获取二维码失败");
            }

            @Override
            public void onComplete() {

            }
        }); //
    }

    private void setWxCodeHandler() {
        if(mHandler != null){
            mHandler.removeMessages(100);
            mHandler.sendEmptyMessageDelayed(100, 5000);
        }
    }


    /**
     * 循环检测  微信是否登录
     */
    private void setHandler() {
        if (mHandler != null){
            mHandler.removeMessages(1);
            mHandler.sendEmptyMessage(1);
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        if (mHandler != null) {
            mHandler = null;
        }
    }
}
